package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.entity.base.TbCountry;
import com.ys.entity.eKnowAi.EKnowKnowledgeList;
import com.ys.entity.storage.*;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.storage.StorageMapper;
import com.ys.service.storage.TccLogisticsChannelMaintService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-05
 * @Description: 物流渠道维护
 * @Version: 1.5
 */
@Controller
@RequestMapping("/api/inter/tccLogisticsChannelMaint")
public class ApiInterTccLogisticsChannelMaintController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsChannelMaintController.class);

    @Autowired
    private TccLogisticsChannelMaintService tccLogisticsChannelMaintService;

    @Autowired
    private CommonApiService<TccLogisticsChannelMaint> commonApiService;

    //菜单id
    private Long menuId = MenuId.TCC_LogisticsChannelMaint;

    @Autowired
    private StorageMapper storageMapper;
    /**
     * 查询
     */
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccLogisticsChannelMaint cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }



    /**
     /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccLogisticsChannelMaint setSeachSql(TccLogisticsChannelMaint cond){

        cond.addLeftJoin("TCC_Warehouse B ON B.Cck=A.Cck")
                .addLeftJoin("TCC_LogisticsServiceProvider D ON D.ProviderBid=A.ProviderCode")
                .addLeftJoin("TB_Country C ON C.Code=A.Country")
                .addField("B.Vck vck,C.Name countryName,D.Abbreviation providerName")
                //排序
                .setOrderby("A.logsticsChannelName ASC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }



    @RequestMapping("/searchFbaPlan")
    @ResponseBody
    public LayuiTableVoJA searchFbaPlan(@ModelAttribute TccLogisticsChannelMaint cond,Long shopId){
        cond    .addField("case when divisionalRule = 0 then '0.1kg进1kg' when divisionalRule = 1 then '0.5kg进1kg' else '不约分' end as divisionalRuleName")//约分规则
                .addField("case when coefficientWeight = 0 then '5000'else '6000' end as coefficientWeightName")//抛货系数
                .addLeftJoin("TCC_Warehouse F ON F.Cck = A.Cck")
                .addLeftJoin("TP_AmazonShop B ON B.id = " + shopId)
                .addLeftJoin("TB_Site C ON C.id = B.SiteId")
                .addLeftJoin("TB_Country D ON D.id = C.CountryId")
                .setStatus(1)
                .where("D.Code = A.Country")
        ;
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }


    /*
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R add(HttpServletRequest request,@RequestParam Map<String, Object> params) {
        try {

            //修改
            return tccLogisticsChannelMaintService.add( params, menuId);
        } catch (Exception e) {
            logger.error("物流方式维护新增出错：", e.getMessage(), e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R edit(HttpServletRequest request,@RequestParam Map<String, Object> params ) {
        try {
            return tccLogisticsChannelMaintService.save(params, menuId);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccLogisticsChannelMaint cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond)
                    .addField("CASE WHEN A.TransportationId=0 THEN '快递' WHEN A.TransportationId=1 THEN '空运'" +
                            "WHEN A.TransportationId=2 THEN '卡航' WHEN A.TransportationId=3 THEN '铁路' " +
                            "WHEN A.TransportationId=4 THEN '海运' END  transportationName")
                    .addField("CASE WHEN A.NameLogsticsClearance=1 THEN '包税' WHEN A.NameLogsticsClearance=0 THEN '自税'" +
                            " END logsticsClearanceName");

            TccLogisticsChannelMaint tccLogisticsChannelMaint = JSON.parseObject(JSON.toJSONString(cond), TccLogisticsChannelMaint.class);
            TccWarehouse tccWarehouse = JSON.parseObject(JSON.toJSONString(cond), TccWarehouse.class);
            TbCountry tbCountry = new TbCountry().setCode(cond.getCountry());

            String transportationName = ConditionUtil.getConditionValue(conditions, "transportationId");//运输类型

            String nameLogsticsClearance = ConditionUtil.getConditionValue(conditions, "nameLogsticsClearance");//清关方式

            String logsticsWay = ConditionUtil.getConditionValue(conditions, "logsticsWay");//物流服务名称
            if (logsticsWay != null){
                cond.where("[逸博" + tccWarehouse.getVck()+"]" +tbCountry.getName()+transportationName+"("+nameLogsticsClearance+")"+
                        tccLogisticsChannelMaint.getEstimatedDayFrom()+"~"+ tccLogisticsChannelMaint.getEstimatedDayTo()+"天"  );
            }

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setFrontExport(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccLogisticsChannelMaint> util = new ExportExcelUtils<>(new TccLogisticsChannelMaint());
            String toFilePath = util.exportExcel(listData, listField, "物流渠道维护");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    @RequestMapping("/searchPlan")
    @ResponseBody
    public LayuiTableVoJA searchPlan(@ModelAttribute TccLogisticsChannelMaint cond,String nameLogsticsClearanceTrue){
        cond = setSeachSql(cond);
        if (nameLogsticsClearanceTrue != null){
            if (nameLogsticsClearanceTrue.equals("6")){
                cond.where("A.nameLogsticsClearance != 1" );
            }

        }
        return commonApiService.searchLay(cond);
    }

    @RequestMapping("/searchZb")
    @ResponseBody
    public R searchZb(HttpServletRequest request,@RequestParam Long id) {
        //计重抛重
        List<TccLogisticsChannelMaintItem> tccLogisticsList = new TccLogisticsChannelMaintItem()
                .setMethodId(id)
                .queryList();
        List<TccLogisticsChannelMaintItem> tccLogisticsOne = tccLogisticsList.stream().filter(item->item.getChannelMaintType() == 0).collect(Collectors.toList());

        List<TccLogisticsChannelMaintItem> tccLogisticsThree = tccLogisticsList.stream().filter(item->item.getChannelMaintType() == 1).collect(Collectors.toList());

        List<TccLogisticsChannelMaintItemSon> tccLogisticsTwo = new TccLogisticsChannelMaintItemSon()
                .setMethodId(id)
                .queryList();

        List<Map<String, Object>> tccLogisticsFour = new TccAdditionalBillingMaint()
                .setMethodId(id)
                .queryMap();


        Map<String,Object> map = new HashMap<>();
        map.put("tccLogisticsOne",tccLogisticsOne);
        map.put("tccLogisticsTwo",tccLogisticsTwo);
        map.put("tccLogisticsThree",tccLogisticsThree);
        map.put("tccLogisticsFour",tccLogisticsFour);
        return R.ok(map);
    }

}
